<?php

namespace App\Admin\Controllers;

use App\Models\Admin\AddressModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class AddressController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'App\Models\Admin\AddressModel';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new AddressModel);

        $grid->column('id', __('Id'));
        $grid->column('name', __('Name'));
        $grid->column('parent_id', __('Parent id'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(AddressModel::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', __('Name'));
        $show->field('parent_id', __('Parent id'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new AddressModel);

        $form->text('name', __('Name'));
        $form->number('parent_id', __('Parent id'));

        return $form;
    }


    /**
     * 获取省
     */
    public function province(){

        $province = AddressModel::where('parent_id','=',0)
            -> get(['id', \DB::raw('name as text')])
            -> toArray();

        foreach ($province as $k => $v){
            $v['id'] = $v['text'];
            $province[$k] = $v;
        }

        return $province;
    }


    /**
     * @method get
     * 获取市
     * @param int $provinceId 省份id
     */
    public function city(Request $request){

        $provinceId = AddressModel::select([
                'id',
                'name as text'
            ])
            -> where('name','=',$request -> input('q'))
            -> value('id');
        if(!$provinceId){
            return null;
        }

        $city = AddressModel::where('parent_id','=',$provinceId)
            -> get(['id', \DB::raw('name as text')])
            -> toArray();

        foreach ($city as $k => $v){
            $v['id'] = $v['text'];
            $city[$k] = $v;
        }

        return $city;
    }
}
